package cn.zlj.pethome.user.service.impl;

import cn.zlj.pethome.basic.service.impl.BaseServiceImpl;
import cn.zlj.pethome.basic.config.BussinessException;
import cn.zlj.pethome.basic.contant.BaseConstants;
import cn.zlj.pethome.basic.mapper.LogininfoMapper;
import cn.zlj.pethome.basic.util.HttpUtil;
import cn.zlj.pethome.user.domain.User;
import cn.zlj.pethome.user.domain.Wxuser;
import cn.zlj.pethome.user.dto.WechatLoginDto;
import cn.zlj.pethome.user.mapper.UserMapper;
import cn.zlj.pethome.user.mapper.WxuserMapper;
import cn.zlj.pethome.user.service.IWxuserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zlj
 * @since 2022-10-23
 */
@Service
public class WxuserServiceImpl extends BaseServiceImpl<Wxuser> implements IWxuserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    public Map<String,Object> binder(WechatLoginDto wechatLoginDto) {
        //非空判断
        if(StringUtils.isBlank(wechatLoginDto.getPhone())||StringUtils.isBlank(wechatLoginDto.getAccessToken())||StringUtils.isBlank(wechatLoginDto.getVerifyCode())){
            throw new BussinessException("绑定异常");
        }
        //判断验证码是否一致
        String yzm =(String) redisTemplate.opsForValue().get(String.format(BaseConstants.VerifyCodeConstants.BUSINESS_BINDER_PREFIX, wechatLoginDto.getPhone()));
        if(StringUtils.isBlank(yzm)){
            throw new BussinessException("验证码错误");
        }
      String [] msgCode=yzm.split(":");
        if(!msgCode[0].equals(wechatLoginDto.getVerifyCode())){
            throw new BussinessException("验证码错误");
        }
        //根据token获取微信信息
        String url=String.format(BaseConstants.WxLoginCons.WX_LOGIN_USER_INFO,wechatLoginDto.getAccessToken(),wechatLoginDto.getOpenId());
        String json = HttpUtil.httpGet(url);
        // json字符串转成 我们的实体
        Wxuser wxuser = JSONObject.parseObject(json, Wxuser.class);
        //判断该手机号是否已经被绑定
        User user = userMapper.findByPhone(wechatLoginDto.getPhone());
        if(user==null){
        }else {
           logininfoMapper.findByUserId(user.getId());
        }
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        return null;
    }
}
